<template>
  <div class="edit-Order-form">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="demo-form" v-loading="uploadLoading"
      element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)">
      <el-form-item label="项目" prop="projectId">
        <!-- <el-select v-model="form.projectId" placeholder="请选择项目">
          <el-option
            v-for="item in projectList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select> -->
        <el-button style="width: fit-content;" @click="openChooseProjectWindow">{{
          form.projectId ? currentProject : '选择项目'
          }}</el-button>
      </el-form-item>

      <!-- <el-form-item label="项目需求" prop="projectDemand">
        <div class="project_demand_text">
          <el-input type="textarea" :rows="6" placeholder="请输入项目需求" v-model="form.projectDemand" maxlength="1000"
            show-word-limit>
          </el-input>
        </div>
      </el-form-item> -->

      <el-form-item label="订单类型" prop="fileType">
        <el-select v-model="form.fileType" placeholder="请选择订单类型">
          <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="文件" prop="fileMsg">
                <el-upload
                    class="upload-demo"
                    drag
                    :on-success="handleAvatarSuccessFile"
                    :on-progress="uploadFileLoading"
                    :data="{ token: $store.state.token }"
                    :headers="{ 'Access-Control-Allow-Origin': '*' }"
                    action="/checkorder/manager/pc/user/importExcel"
                    :show-file-list="false"
                    multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>
            </el-form-item> -->

      <el-form-item label="文件" prop="fileMsg">
        <el-upload class="upload-demo" drag :action="url" :on-progress="uploadFileLoading"
          :data="{ token: $store.state.token, fileType: this.form.fileType }"
          :headers="{ 'Access-Control-Allow-Origin': '*' }" :show-file-list="false" :http-request="checkedFile"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>

      <el-form-item v-if="goodList && goodList.length > 0 && this.form.fileType == 1">
        <div class="form_table_goods">
          <el-table :data="goodList" :summary-method="getSummaries" show-summary max-height="750"
            :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" style="width: 100%">
            <el-table-column prop="goodName" fixed label="商品名称">
            </el-table-column>
            <el-table-column prop="goodSkuName" fixed label="商品规格">
            </el-table-column>
            <el-table-column prop="expirationDate" label="有效期至">
            </el-table-column>
            <el-table-column prop="warrantyDate" label="保质期">
            </el-table-column>
            <el-table-column prop="goodNum" label="数量"> </el-table-column>
            <el-table-column prop="goodPrice" label="旗舰店售卖价">
            </el-table-column>
            <el-table-column prop="goodOnlineLink" show-overflow-tooltip label="天猫/京东链接">
            </el-table-column>
            <el-table-column prop="goodPic" label="图片">
              <template slot-scope="scope">
                <el-image v-if="scope.row.goodPic" style="width: 100px; height: 100px" :src="scope.row.goodPic"
                  :preview-src-list="[scope.row.goodPic]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="goodBoxNum" label="箱规（数量）">
            </el-table-column>
            <el-table-column prop="goodBoxNum" label="箱规（尺寸mm）">
            </el-table-column>
            <el-table-column prop="goodBoxSize" label="单个产品包装尺寸mm">
            </el-table-column>
            <el-table-column prop="shopFans" label="店铺粉丝量">
            </el-table-column>
            <el-table-column prop="goodSaleNum" label="产品销量">
            </el-table-column>
            <!-- <el-table-column
                            prop="finalPrice"
                            width="180"
                            label="旗舰店实际成交价">
                        </el-table-column> -->
            <el-table-column prop="realReadPrice" width="180" label="实际成交价">
            </el-table-column>
            <el-table-column prop="totalPrice" fixed="right" label="货值合计">
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item v-if="goodList && goodList.length > 0 && this.form.fileType == 2">
        <div class="form_table_goods">
          <el-table :data="goodList" :summary-method="getSummaries" show-summary max-height="750"
            :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" style="width: 100%">
            <el-table-column prop="chainStoreName" fixed label="连锁店铺名称">
            </el-table-column>
            <el-table-column prop="category" fixed label="连锁店铺名称">
            </el-table-column>
            <el-table-column prop="storeNumber" label="店铺数量">
            </el-table-column>
            <el-table-column prop="averageScore" label="美团/大众点评店铺平均评分">
            </el-table-column>
            <el-table-column prop="validityPeriod" label="有效期">
            </el-table-column>
            <el-table-column prop="distributedCities" label="分布城市">
            </el-table-column>
            <el-table-column prop="productName" label="产品名称">
            </el-table-column>
            <el-table-column prop="price" label="价值"> </el-table-column>
            <el-table-column prop="num" label="数量"> </el-table-column>
            <el-table-column prop="useRights" label="使用权益">
            </el-table-column>
            <el-table-column prop="couponForm" label="卡券形式">
            </el-table-column>
            <el-table-column prop="usageRestrictions" label="使用限制">
            </el-table-column>
            <el-table-column prop="storeLinks" show-overflow-tooltip label="店铺链接（美团、携程等）">
            </el-table-column>
            <el-table-column prop="verificationProcess" label="核销流程">
            </el-table-column>
            <el-table-column prop="finalPrice" label="实际成交价">
            </el-table-column>
            <el-table-column prop="totalPrice" fixed="right" label="合计">
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item v-if="goodList && goodList.length > 0 && this.form.fileType == 3">
        <div class="form_table_goods">
          <el-table :data="goodList" :summary-method="getSummaries" show-summary max-height="750"
            :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" style="width: 100%">
            <el-table-column prop="hotelName" fixed label="酒店名称">
            </el-table-column>
            <el-table-column prop="hotelAddress" fixed label="酒店地址">
            </el-table-column>
            <el-table-column prop="busyTime" label="旺季时间">
            </el-table-column>
            <el-table-column prop="hotelType" label="房型"> </el-table-column>
            <el-table-column prop="expirationDate" label="有效期">
            </el-table-column>
            <el-table-column prop="isHaveMorning" label="是否含早"></el-table-column>
            <el-table-column prop="num" label="数量"></el-table-column>
            <el-table-column prop="price" label="平台价"> </el-table-column>
            <el-table-column prop="url" show-overflow-tooltip label="链接">
            </el-table-column>
            <el-table-column prop="hotelPic" label="房间图片">
              <template slot-scope="scope">
                <el-image v-if="scope.row.hotelPic" style="width: 100px; height: 100px" :src="scope.row.hotelPic"
                  :preview-src-list="[scope.row.hotelPic]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column prop="realPrice" width="180" label="实际成交价">
            </el-table-column>
            <el-table-column prop="totalPrice" fixed="right" label="房值合计">
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave()">立即提交</el-button>
        <!-- <el-button @click="handleResetForm()">重置</el-button> -->
      </el-form-item>
    </el-form>

    <!-- 选择项目弹窗 -->
    <el-dialog title="项目" :visible.sync="projectChooseShow">
      <el-form inline label-width="80px" :model="projectSearchParams" ref="projectSearchParamsRef">
        <el-form-item label="关键字" prop="keyword">
          <el-input v-model="projectSearchParams.keyword" placeholder="客户公司名称、项目或品名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetProjectList" size="small ">重置</el-button>
          <el-button type="primary" @click="getProjectList" size="small ">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="projectList" @row-click="handleProjectRowClick" :row-class-name="projectRowClassName">
        <el-table-column property="value" label="项目id"></el-table-column>
        <el-table-column property="label" label="项目名称"></el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChangeProject" @current-change="handleCurrentChangeProject"
        :current-page="currentProjectPage" :page-sizes="[10, 20, 50, 100]" :page-size="ProjectPageSize"
        layout="->,total, sizes, prev, pager, next" :total="totalProject" style="margin-top: 20px;">
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import APIOrder from "@/api/apiOrder";
import APIProjectFile from "@/api/apiProjectFile";
import APIProject from "@/api/apiProject";
import qs from "qs";
import axios from "axios";

export default {
  name: "EditOrderForm",
  data() {
    return {
      editDialogTitle: "",
      tokenData: {
        token: localStorage.getItem("mujingtoken"),
      },
      id: null,
      // 地图
      form: {
        projectId: null,
        fileType: 1,
        fileMsg: 1,
      },
      currentProject: "",
      rules: {
        projectId: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        fileType: [
          { required: true, message: "请选择订单类型", trigger: "change" },
        ],
        projectDemand: [
          { required: true, message: "请输入项目需求", trigger: "input" },
        ],

        // fileMsg: [
        //     { required: true, message: "请上传文件", trigger: "change" },
        // ],
      },
      isRecommendOptions: [
        {
          value: 1,
          label: "不推荐",
        },
        {
          value: 2,
          label: "推荐",
        },
      ],
      html: "",
      projectList: [],
      totalProject: 0,
      orderTypeList: [
        {
          value: 1,
          label: "核价订单",
          departId: -1,
        },
        {
          value: 2,
          label: "本地生活",
          departId: 5032,
        },
        {
          value: 3,
          label: "酒店民宿",
          departId: 5033,
        },
      ],
      goodList: [],
      updateFileList: [],
      uploadLoading: false,
      url: "",
      projectChooseShow: false,
      currentProjectPage: 1,
      ProjectPageSize: 10,
      projectPaginationList: [], //分页列表
      projectSearchParams: {
        keyword: "",
      }, // 项目搜索参数
      // 项目文件
      projectFile: null,
    };
  },
  activated() {
    console.log("========>", process.env.VUE_APP_REQUSET_URL)
    // this.url = "https://checkorder.mejour.cn/checkorder/manager/pc/user/importExcel?token=" + this.$store.state.token;
    // this.url =
    //   "http://192.168.110.113:9003/checkorder/manager/pc/user/importExcel?token=" +
    //   this.$store.state.token;
    //this.url = process.env.VUE_APP_REQUSET_URL + "/checkorder/manager/pc/user/importExcel?token=" + this.$store.state.token;
    this.url = `/checkorder/manager/pc/user/importExcel?token=${this.$store.state.token}`;
    (async () => {
      await this.getProjectList();
      if (this.$route.query.row) {
        let row = qs.parse(JSON.parse(this.$route.query.row));
        this.form = row;
      } else {
        this.handleResetForm();
      }
      if (this.$route.query && this.$route.query.projectId) {
        this.form.projectId = parseInt(this.$route.query.projectId);
        this.currentProject = this.$route.query.projectName;
      }
      this.goodList = [];
      this.handleDepartId();
    })();
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let sumColums = [];
      if (this.form.fileType == 1) {
        sumColums = ["goodNum", "goodPrice", "totalPrice"];
      } else if (this.form.fileType == 2) {
        sumColums = ["num", "price", "totalPrice"];
      } else if (this.form.fileType == 3) {
        sumColums = ["num", "price", "totalPrice"];
      }
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          !values.every((value) => isNaN(value)) &&
          sumColums.includes(column.property)
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += " 元";
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    handleDepartId() {
      const departId = this.$route.query.departId;
      const orderType = this.orderTypeList.find(
        (item) => item.departId == departId
      );
      this.form.fileType = orderType !== undefined ? orderType.value : 1;
      
    },
    openChooseProjectWindow() {
      this.projectChooseShow = true;
    },
    handleSizeChangeProject(val) {
      this.ProjectPageSize = val;
      this.getProjectList();
      // this.projectPaginationList = this.projectList.slice((this.currentProjectPage - 1) * this.ProjectPageSize, this.currentProjectPage * this.ProjectPageSize)
    },
    handleCurrentChangeProject(val) {
      this.currentProjectPage = val;
      this.getProjectList();
      // this.projectPaginationList = this.projectList.slice((this.currentProjectPage - 1) * this.ProjectPageSize, this.currentProjectPage * this.ProjectPageSize)
    },
    checkedFile(obj) {
      let that = this;
      let url = this.url;
      this.projectFile = obj.file
      const formData = new FormData();
      formData.append("file", obj.file); //file 和 后端字段要保持一致
      formData.append("token", this.$store.state.token);
      formData.append("fileType", this.form.fileType);
      const config = {
        headers: {
          "Access-Control-Allow-Origin": "*",
          token: this.$store.state.token,
        },
        timeout: 1000 * 60 * 10, //这里2分钟内的配置是生效的，超过了就不行。。
      };
      const loading = this.$loading({
        lock: true,
        text:
          "导入中，若数据量过大，则时间较长，在此期间请勿操作，请等待......",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      return axios
        .post(url, formData, config)
        .then((rs) => {
          if (rs.status === 200) {
            let data = rs.data;
            if (data.key === 1000) {
              that.$message.success({
                showClose: true,
                message: "上传成功",
                duration: 1500,
              });
              that.goodList = [];
              let goodList = data.result.list;

              if (this.form.fileType == 1) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.goodNum * item.goodPrice).toFixed(2);
                });
              } else if (this.form.fileType == 2) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.num * item.price).toFixed(2);
                });
              } else if (this.form.fileType == 3) {
                goodList.forEach((item) => {
                  item.totalPrice = (item.num * item.price).toFixed(2);
                });
              }
              that.goodList = goodList;
            } else {
              that.$message({
                type: "warning",
                message: rs.data.message,
              });
            }
          } else {
            that.$message({
              type: "warning",
              message: rs,
            });
          }
          loading.close();
        })
        .catch((rs) => {
          loading.close();
          this.$message({
            type: "error",
            message: rs,
          });
        });
    },
    uploadFileLoading(e) {
      this.uploadLoading = true;
    },
    handleAvatarSuccessFile: function(e, file, flieList) {
      this.goodList = [];
      this.uploadLoading = false;
      if (e.key == 1000) {
        let goodList = e.result.list;
        goodList.forEach((item) => {
          item.totalPrice = (item.goodNum * item.goodPrice).toFixed(2);
        });
        this.goodList = goodList;
        this.$message.success({
          showClose: true,
          message: "上传成功",
          duration: 1500,
        });
      } else if (e.key == 1001) {
        localStorage.removeItem("mujinguserInfo");
        localStorage.removeItem("mujingtoken");
        localStorage.removeItem("mujingpermissionList");
        localStorage.removeItem("mujingpermissionNameList");
        location.reload();
      } else {
        this.$message.error({
          showClose: true,
          message: e.message,
          duration: 1500,
        });
      }
    },
    async getProjectList() {
      this.tableLoading = true;
      const params = {
        token: this.$store.state.token,
        pageNum: this.currentProjectPage,
        pageSize: this.ProjectPageSize,
        ...this.projectSearchParams,
      };
      let res = await APIProject.getProjectManageList(params);
      if (res.key === 1000) {
        this.totalProject = res.result.count;
        res = res.result;
        let list = [];
        res.list.forEach((item) => {
          list.push({
            label: item.brands,
            value: item.id,
          });
        });
        this.projectList = list;
        this.tableLoading = false;
      }
      //   this.projectPaginationList = this.projectList.slice((this.currentProjectPage - 1) * this.ProjectPageSize, this.currentProjectPage * this.ProjectPageSize)

      //   APIProject.getProjectManageList(params).then((res) => {
      //     if (res.key === 1000) {
      //       res = res.result;
      //       let list = [];
      //       res.list.forEach((item) => {
      //         list.push({
      //           label: item.brands,
      //           value: item.id,
      //         });
      //       }); 
      //       this.projectList = list;
      //       this.tableLoading = false;
      //     }
      //   });
    },
    resetProjectList() {
      this.currentProjectPage = 1;
      this.$refs.projectSearchParamsRef.resetFields();
      this.getProjectList();
    },
    handleProjectRowClick(row) {
      this.form.projectId = row.value;
      this.currentProject = this.projectList.find(
        (pro) => pro.value == this.form.projectId
      ).label;
      this.projectChooseShow = false;
    },
    projectRowClassName({ row, rowIndex }) {
      if (row.value == this.form.projectId) {
        return "success-row";
      } else {
        return "";
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          this.$message({
            type: "warning",
            message: "请检查上面输入项",
          });
          return;
        }
        if (!this.goodList || this.goodList.length < 1) {
          this.$message({
            type: "warning",
            message: "请上传文件",
          });
          return;
        }
        this.$bus.$emit("show-loading", true);
        const params = {
          projectId: this.form.projectId,
          fileType: this.form.fileType,
          goods: JSON.stringify(this.goodList),
        };
        if (!params.projectId) {
          APIOrder.sendOrderUpdate(params, "application/json").then((res) => {
            if (res.key === 1000) {
              this.goodList = [];
              this.$router.go(-1);
            }
            this.$bus.$emit("show-loading", false);
          });
        } else {
          APIOrder.sendOrder(params, "application/json").then((res) => {
            if (res.key === 1000) {
              this.submitProjectFile()
              this.$router.go(-1);
            }
            this.$bus.$emit("show-loading", false);
          });
        }
      });
    },
    handleResetForm() {
      this.form = {
        projectId: null,
        fileType: null,
        file: null,
      };
      this.$refs.form.clearValidate();
    },
    submitProjectFile(){
      const params = {
        file: this.projectFile,
        projectId: this.form.projectId,
        fileType: 5122
      }
      APIProjectFile.doAddProjectFile(params).then((res) => {
        console.log("res====", res)
      });
    },
  },
};
</script>
<style scoped lang="scss">
:deep(.el-table .success-row) {
  background: rgb(213, 236, 241);
}
.project_demand_text{
  width: 80%;
}
</style>
<style lang="sass">

.edit-Order-form
  //.el-input__inner
  //  border: none
  //  background: #F4F6F9!important
  .el-input__count
    background: #F4F6F9!important
  .el-button--primary
    width: 94px
    height: 40px
    //box-shadow: 0px 5px 12px 0px rgba(24, 97, 253, 0.43)
    //background: #1861FD
  .el-button--default
    width: 94px
    height: 40px
    border-radius: 4px
    //border: 1px solid #1861FD
    //color: #1861FD
</style>
<style lang="sass" scoped>
.form_table_goods
    width: 90%
.edit-Order-form
  @include container
  padding-top: 36px
.global-form-dialog
  .el-dialog__body
    padding: 30px 50px
.map-container
  display: flex
  .amap-wrapper2
    width: 550px
    height: 500px
    margin-right: 24px
  .map-list
    width: 300px
    height: 500px
    overflow-y: auto
    .map-item
      cursor: pointer
      margin-bottom: 15px
      padding: 6px
      border-radius: 4px
      &.active
        background: $main-color
        color: #fff
      &:last-child
        margin-bottom: 0
      p
        line-height: 22px
.type-group
  display: flex
  flex-direction: row
  flex-wrap: nowrap
  .type-item
    width: 153px
    height: 46px
    text-align: center
    line-height: 46px
    border-radius: 3px
    cursor: pointer
    margin-right: 19px
    &.active
      background-color: #1861FD
      color: #FFFFFF
    &.unactive
      border: 1px solid #1861FD
      color: #222222
</style>
